/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.spice.im.group;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.beem.push.utils.AsyncTask;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.BaseActivity;
import com.spice.im.ContactFrameActivity;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.OtherProfileActivity;
import com.spice.im.R;
import com.spice.im.SpiceApplication;
import com.spice.im.attendance.AttendanceActivity2;
//import com.spice.im.group.GroupDetailsActivity.OnRightImageButtonClickListener;
import com.spice.im.group.GroupDetailsActivity.exPhoneCallListener;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.DialogUtil;
//import com.spice.im.group.GroupDetailsActivity.GridAdapter;
//import com.spice.im.group.GroupDetailsActivity.BeemServiceConnection;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.MyDialog;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onMiddleImageButtonClickListener;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.spice.im.utils.MyDialog.MyDialogListener;
import com.stb.core.chat.ContactGroup;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.ui.feed.AddDynamicsActivity;
import com.stb.isharemessage.ui.feed.OtherFeedListActivity;
import com.stb.isharemessage.utils.BeemConnectivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;


public class GroupMemberActivity extends Activity implements IConnectionStatusCallback,OnClickListener {
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));
	}
	private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    protected FlippingLoadingDialog mLoadingDialog;
    private HeaderLayout mHeaderLayout;
	
    private static final String TAG = "GroupMembersActivity";
    private final ServiceConnection mServConn = new BeemServiceConnection();
    
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}		    
	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
    
//    private static final int REQUEST_CODE_ADD_USER = 0;
    private static final int REQUEST_CODE_EDIT_GROUPNAME = 5;
    
//	public static final String TAG = "GroupsActivity";
	private static final int MESSAGE_REFRESH_LAYOUT=0x00020001;
    private String groupId;
    private String groupName;
    private String tagimg;
    private String invitetag;//0 代表被邀请
    
	
	private ListView groupListView;
//	protected List<MemberInfo.MemberItem> grouplist;
    private List<ContactGroup> memberItems,allMemberItems;
	private GridAdapter groupAdapter;
	boolean add;
	boolean at;
	String idString;
	private static final int REQUEST_CODE_ADD_USER = 0;
	private ProgressDialog progressDialog;
//	private EMGroup group;
	DeleteDialog deleteDialog;
	Dialog dialog2;
	String st = "";
	
	private Context mContext;
    //网络状态start
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
    //网络状态end
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		add = getIntent().getBooleanExtra("add", false);
		at = getIntent().getBooleanExtra("at", false);
		idString = getIntent().getStringExtra("id");
		groupId = idString;
		CurrentName = getIntent().getStringExtra("CurrentName");
		CurrentAvatarpath = getIntent().getStringExtra("CurrentAvatarpath");
		OwnerUid = getIntent().getStringExtra("OwnerUid");
		allMemberItems = (List<ContactGroup>) getIntent().getSerializableExtra("member");
//		addBtn = (ImageButton) actionBarView.findViewById(R.id.addBtn);
//		if (add) {
//			addBtn.setVisibility(View.VISIBLE);
//		}
//		
//		addBtn.setOnClickListener(this);
//		setTitle("全部成员");
		setContentView(R.layout.member_layout);
		mContext = this;
		st = getResources().getString(R.string.people);
        mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
        mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
		
//        mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
//		mHeaderLayout.setTitleRightImageButton("聊天信息", null,
//				R.drawable.return2,
//				new OnRightImageButtonClickListener());
		mHeaderLayout.init(HeaderStyle.TITLE_CHAT);
		mHeaderLayout.setTitleChat(R.drawable.ic_chat_dis_1,
				R.drawable.bg_chat_dis_active, "全部成员",
				"",
				R.drawable.ic_menu_invite,//ic_menu_invite  ic_topbar_profile
				new OnMiddleImageButtonClickListener(),
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
		groupListView = (ListView) findViewById(R.id.list);
		// show group list
		if (allMemberItems == null) {
			allMemberItems = new ArrayList<ContactGroup>();
		}
		groupAdapter = new GridAdapter(this, allMemberItems);
		groupListView.setAdapter(groupAdapter);
//		group = EMClient.getInstance().groupManager().getGroup(idString);
		groupListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
//				deleteDialog = new DeleteDialog(GroupMemberActivity.this, new onclick(allMemberItems.get(arg2), arg2));
//				deleteDialog.show();
				final int position = arg2;
				dialog2 =null;		
				dialog2 = DialogUtil.getMyDialog("删除群组用户",
								"您确定要删除用户"+allMemberItems.get(arg2).getName()+"吗?",
								GroupMemberActivity.this, new MyDialogListener() {
									
									@Override
									public void onPositiveClick(Dialog dialog, View view) {
//										upload2share(age);
										String st12 = getResources().getString(R.string.not_delete_myself);
										if (!CurrentUid.equals(OwnerUid)) {
											Toast.makeText(getApplicationContext(), "只有管理员才可以删除", Toast.LENGTH_LONG).show();
											return;
										}
//										if (EMClient.getInstance().getCurrentUser().equals("user_" + username.getUid())) {
//							                new EaseAlertDialog(GroupMemberActivity.this, st12).show();
//							                return;
//							            }
//							            if (!NetUtils.hasNetwork(getApplicationContext())) {
//							                Toast.makeText(getApplicationContext(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
//							                return;
//							            }
							            deleteMembersFromGroup(allMemberItems.get(position).getUid(),position);
									}
									
									@Override
									public void onNegativeClick(Dialog dialog, View view) {
										
									}
								}, MyDialog.ButtonBoth);
				dialog2.show();
				
				return true;
			}
		});
		
		groupListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (at) {
					Intent i = new Intent();
					i.putExtra("user_name", allMemberItems.get(arg2).getUsername());
					setResult(RESULT_OK, i);
					finish();
				} else {
					Bundle bundle = new Bundle();
					bundle.putString("uid", allMemberItems.get(arg2).getUid());
					bundle.putString("searchkey", allMemberItems.get(arg2).getUsername());
					bundle.putInt("type", 1);
					Intent intent = new Intent();
					intent.setClass(GroupMemberActivity.this, OtherProfileActivity.class);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			}
		});
		if (allMemberItems == null || allMemberItems.size() == 0) {
            
		}

        //网络状态start
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
	    //网络状态end
        
        BeemApplication.getInstance().addActivity(this);
        
	}
	
	class onclick implements OnClickListener{

		ContactGroup username;
		int position;
		public onclick(ContactGroup username,int position) {
			this.username = username;
			this.position = position;
		}
		
		@Override
		public void onClick(View arg0) {
			deleteDialog.cancel();
			String st12 = getResources().getString(R.string.not_delete_myself);
			if (!CurrentUid.equals(OwnerUid)) {
				Toast.makeText(getApplicationContext(), "只有管理员才可以删除", Toast.LENGTH_LONG).show();
				return;
			}
//			if (EMClient.getInstance().getCurrentUser().equals("user_" + username.getUid())) {
//                new EaseAlertDialog(GroupMemberActivity.this, st12).show();
//                return;
//            }
//            if (!NetUtils.hasNetwork(getApplicationContext())) {
//                Toast.makeText(getApplicationContext(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
//                return;
//            }
            deleteMembersFromGroup(username.getUid(),position);
		}
		
	}
	
	protected void deleteMembersFromGroup(final String username,final int  p) {
		String st13 = getResources().getString(R.string.Are_removed);
        final String st14 = getResources().getString(R.string.Delete_failed);
        final ProgressDialog deleteDialog = new ProgressDialog(GroupMemberActivity.this);
        deleteDialog.setMessage(st13);
        deleteDialog.setCanceledOnTouchOutside(false);
        deleteDialog.show();
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    // 删除被选中的成员
//					EMClient.getInstance().groupManager().removeUserFromGroup(idString, username);
                	initExitGroup(groupId,username);
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            deleteDialog.dismiss();
                            allMemberItems.remove(p);
                            groupAdapter.notifyDataSetChanged();
                        }
                    });
                } catch (final Exception e) {
                    deleteDialog.dismiss();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(getApplicationContext(), st14 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }
        }).start();
    }

	/**
	 * 进入公开群聊列表
	 */
	public void onPublicGroups(View view) {
		// startActivity(new Intent(this, PublicGroupsActivity.class));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String st1 = getResources().getString(R.string.being_added);
        String st2 = getResources().getString(R.string.is_quit_the_group_chat);
        String st3 = getResources().getString(R.string.chatting_is_dissolution);
        String st4 = getResources().getString(R.string.are_empty_group_of_news);
        String st5 = getResources().getString(R.string.is_modify_the_group_name);
        final String st6 = getResources().getString(R.string.Modify_the_group_name_successful);
        final String st7 = getResources().getString(R.string.change_the_group_name_failed_please);

        if (resultCode == RESULT_OK) {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(GroupMemberActivity.this);
                progressDialog.setMessage(st1);
                progressDialog.setCanceledOnTouchOutside(false);
            }
            switch (requestCode) {
                case REQUEST_CODE_ADD_USER:// 添加群成员
//                    final String[] newmembers = data.getStringArrayExtra("newmembers");
//                    progressDialog.setMessage(st1);
//                    progressDialog.show();
//                    addMembersToGroup(newmembers);
                    final List<ContactGroup> friends_cGroup_select = (List<ContactGroup>)data.getSerializableExtra("newmembers");
                    progressDialog.setMessage(st1);
                    progressDialog.show();
                    addMembersToGroup(friends_cGroup_select);
                    break;

                default:
                    break;
            }
        }
    }
	
//	private void addMembersToGroup(final String[] newmembers) {
//        final String st6 = getResources().getString(R.string.Add_group_members_fail);
//        new Thread(new Runnable() {
//
//            public void run() {
//                try {
//                    // 创建者调用add方法
//                	group = EMClient.getInstance().groupManager().getGroup(idString);
//                    if (EMClient.getInstance().getCurrentUser().equals(group.getOwner())) {
//						EMClient.getInstance().groupManager().addUsersToGroup(idString, newmembers);
//                    } else {
//                        // 一般成员调用invite方法
//						EMClient.getInstance().groupManager().inviteUser(idString, newmembers, null);
//                    }
//                    runOnUiThread(new Runnable() {
//                        public void run() {
//
//                            if (!isNetWorkAvailable()) {
//                                handler.obtainMessage(StringConfig.SHOW_TOAST, getResources().getString(R.string.no_network)).sendToTarget();
//                            } else {
//                                RequestServerManager.asyncRequest(0, new RequestGroupInfo(GroupMemberActivity.this, group.getMembers(), new RequestFinishCallback<MemberInfo>() {
//
//                                    @Override
//                                    public void onFinish(final MemberInfo result) {
//                                        // TODO Auto-generated method stub
////                                        handler.obtainMessage(StringConfig.SHOW_TOAST, result.getDescription()).sendToTarget();
//                                        if (result.isSucceed()) {
////                                            runOnUiThread(new Runnable() {
////                                                @Override
////                                                public void run() {
//                                        	grouplist.clear();
//                                        	grouplist.addAll(result.getMemberItemList());
//                                            
//                                        	groupAdapter = null;
//                                        	groupAdapter = new GridAdapter(GroupMemberActivity.this, result.getMemberItemList());
//                                            groupListView.setAdapter(groupAdapter);
//                                        }
////                                            });
//
//                                    }
////                                }
//                                }));
//                            }
//
//
//                        
//
//                            progressDialog.dismiss();
//                        }
//                    });
//                } catch (final Exception e) {
//                    runOnUiThread(new Runnable() {
//                        public void run() {
//                            progressDialog.dismiss();
//                            Toast.makeText(getApplicationContext(), st6 + e.getMessage(), Toast.LENGTH_LONG).show();
//                        }
//                    });
//                }
//            }
//        }).start();
//    }

    /**
     * 增加群成员
     *
     * @param newmembers
     */
    private boolean bol_muninvite = false;
    private void addMembersToGroup(final List<ContactGroup> newmembers) {
        final String st6 = getResources().getString(R.string.Add_group_members_fail);
        new Thread(new Runnable() {

            public void run() {
                try {
                    // 创建者调用add方法
                    if (CurrentUid.equals(OwnerUid)) {
//                        EMClient.getInstance().groupManager().addUsersToGroup(groupId, newmembers);
                    	if(newmembers!=null
                    			&& newmembers.size()!=0){
                    		String ids = "";
                    		ContactGroup di;
                    		for(int i=0;i<newmembers.size()-1;i++){
                    			di = (ContactGroup)newmembers.get(i);
                    			if(di.getJID().indexOf("@0/")!=-1)
                    			ids += di.getJID().replace("@0/", "|") + ",";
                    		}
                    		di = (ContactGroup)newmembers.get(newmembers.size()-1);
                    		if(di.getJID().indexOf("@0/")!=-1)
                    		ids += di.getJID().replace("@0/", "|") ;
                    		bol_muninvite = addUsersToGroup(groupId,ids);
                    	}
                    } else {
                        // 一般成员调用invite方法
//                        EMClient.getInstance().groupManager().inviteUser(groupId, newmembers, null);
                    	if(newmembers!=null
                    			&& newmembers.size()!=0){
                    		String ids = "";
                    		ContactGroup di;
                    		for(int i=0;i<newmembers.size()-1;i++){
                    			di = (ContactGroup)newmembers.get(i);
                    			ids += di.getJID().replace("@0/", "|") + ",";
                    		}
                    		di = (ContactGroup)newmembers.get(newmembers.size()-1);
                    		ids += di.getJID().replace("@0/", "|") ;
                    		bol_muninvite = addUsersToGroup(groupId,ids);
                    	}
                    }
                    runOnUiThread(new Runnable() {
                        public void run() {
//                            refreshMembers(group);
                        	if(bol_muninvite)
                        		showCustomToast("群组邀请消息已成功发送!");
                        	else
                        		showCustomToast("群组邀请失败!"+errorMsg[errorType]);
                        	getGroupMembers(groupId);		
                            setTitle(groupName + "(" + AffiliationsCount + st);
                            progressDialog.dismiss();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), st6 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }
    
	@Override
	public void onResume() {
		super.onResume();
		isWork = false;
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
        clearAsyncTask();
	    try{//网络状态相关
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
        if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
		mXmppFacade = null;
		//网络状态start
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		//网络状态end
	}

//	@Override
//	protected boolean handler(Message msg) {
//		// TODO Auto-generated method stub
//		if (super.handler(msg))
//			return true;
//		switch (msg.what) {
//			case MESSAGE_REFRESH_LAYOUT:
//				break;
//			default:
//				break;
//		}
//		return false;
//	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
        switch (v.getId()) {
			//网络设置
	        case R.id.net_status_bar_btn:
				setNetworkMethod(this);
			break;
        }
//		if (v.getId() == R.id.addBtn) {
//			ArrayList<String> s = new ArrayList<String>();
//            if(allMemberItems != null){
//            	for (int i = 0; i < allMemberItems.size(); i++) {
//        			s.add(allMemberItems.get(i).getUid());
//        		}
//            }
//			startActivityForResult(
//                    (new Intent(GroupMemberActivity.this, GroupPickContactsActivity.class).putExtra("groupId", idString).putStringArrayListExtra("member", (ArrayList<String>) s)),
//                    REQUEST_CODE_ADD_USER);
//		}
	}
	protected class OnMiddleImageButtonClickListener implements
	onMiddleImageButtonClickListener {

		@Override
		public void onClick() {
			ArrayList<String> s = new ArrayList<String>();
            if(allMemberItems != null){
            	for (int i = 0; i < allMemberItems.size(); i++) {
        			s.add(allMemberItems.get(i).getUid());
        		}
            }
//			startActivityForResult(
//                    (new Intent(GroupMemberActivity.this, GroupPickContactsActivity.class).putExtra("groupId", idString).putStringArrayListExtra("member", (ArrayList<String>) s)),
//                    REQUEST_CODE_ADD_USER);
			startActivityForResult(
                    (new Intent(GroupMemberActivity.this, GroupNew2Activity.class).putExtra("groupId", groupId).putExtra("CurrentUid", CurrentUid).putExtra("CurrentName", CurrentName).putExtra("CurrentAvatarpath",CurrentAvatarpath)),
                    REQUEST_CODE_ADD_USER);
		}
	}
	private class GridAdapter extends ArrayAdapter<ContactGroup> {

        public boolean isInDeleteMode;
        private List<ContactGroup> objects;
        Context context;

        public GridAdapter(Context context, List<ContactGroup> objects) {
            super(context, 0, objects);
            this.objects = objects;
            isInDeleteMode = false;
            this.context = context;
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.em_member, null);
                holder.imageView = (ImageView) convertView.findViewById(R.id.iv_avatar);
                holder.textView = (TextView) convertView.findViewById(R.id.tv_name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.imageView.setImageResource(R.drawable.empty_photo4);
                final ContactGroup username = getItem(position);
                holder.textView.setText(username.getName());
                String s1 = username.getAvatarPath();
                if(s1!=null
        	    		&& s1.length()!=0
        	    		&& !s1.equalsIgnoreCase("null"))
//                ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+s1, holder.imageView,Options.getOptions(UIUtils.dip2px(context, ConstantConfig.AVATAR_RADIUS)));
                ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+s1, holder.imageView,Options.getOptions(UIUtils.dip2px(context, ConstantConfig.AVATAR_RADIUS)));
                else
                	holder.imageView.setImageResource(R.drawable.empty_photo4);
            return convertView;
        }

        @Override
        public int getCount() {
            return super.getCount();
        }
    }
	
	private static class ViewHolder {
        ImageView imageView;
        TextView textView;
    }
	
	
	/**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;//20130804 added by allen
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(GroupMemberActivity.this);//网络状态相关
		    	    CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		    	}catch(Exception e){}
//		    getGroupMembers(groupId);//有上一个activity传过来的数据，无需联网获取
		    }
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
			 try{//网络状态相关
				    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
				    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
			    }catch (RemoteException e) {
			    	e.printStackTrace();
			    }
		    mXmppFacade = null;
		    mBinded = false;
		}
    }
    private boolean flag = false;
	private boolean isWork = false;
	private void getGroupMembers(final String tagid) {
//		showCustomToast("getGroupMembers1");
		Log.e("================GroupDetailsActivity.java ================", "++++++++++++++getGroupMembers111++++++++++++++");
		if(!isWork){
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				cGroupsList.clear();//清除上次记录
				return initGeGroupMembers(tagid,"1","");
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (result) {	
					mHandler.sendEmptyMessage(1);
				}else{
					//提示没有获取到数据：可能网络问题
					mHandler.sendEmptyMessage(0);
				}
				flag = false;
				isWork = false;
			}

		});
		isWork = true;
		}
	}
    public boolean addUsersToGroup(String tagid,String ids){
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    		MucInviteIQ reqXML = new MucInviteIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
		            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		    	    CurrentUsername = username;
		            reqXML.setUsername(username);
		            reqXML.setTagid(tagid);
		            reqXML.setTagname(groupName);
		            reqXML.setTagimg(tagimg);
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
		            reqXML.setIds(ids);
	//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid+tagid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "mucinviteiq"; 
		    		String namespace = "com:isharemessage:mucinviteiq";
		    		MucInviteIQResponseProvider provider = new MucInviteIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "mucinviteiq", "com:isharemessage:mucinviteiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof MucInviteIQResponse) {
		                	final MucInviteIQResponse mucInviteIQResponse = (MucInviteIQResponse) rt;
	
		                    if (mucInviteIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:mucinviteiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = mucInviteIQResponse.getId();
		                        String Apikey = mucInviteIQResponse.getApikey();
		                        String retcode = mucInviteIQResponse.getRetcode();
		                        String memo = mucInviteIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000")){
		                        	return true;
		                        }
		                        else if(retcode.equalsIgnoreCase("0002")){
		                        	errorType = 6;
		                        	return false;
		                        }else{
		                        	errorType = 5;
		                        	return false;
		                        }
		                    }
		                } 
		            }
		    		errorType = 1;
		            return false;

		    }else
		    	errorType = 1;
		    	return false;
			}else
				errorType = 4;
				return false;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
			return false;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
			return false;
		}
//		return false;
    }
    
	private HashMap cGroups = new HashMap();
    private ArrayList cGroupsList = new ArrayList<ContactGroup>();
    int AffiliationsCount = 0;
    private String OwnerUid = "";
    private String OwnerUsername = "";
    private String CurrentUid = "";
    private String CurrentUsername = "";
    private String CurrentName = "";
    private String CurrentAvatarpath = "";
	private String[] errorMsg = new String[]{"群成员信息获取成功.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"系统错误.群成员信息获取失败.",
			"群成员信息获取失败,hash校验失败"//0002
			};
	private int errorType = 5;
    private boolean initGeGroupMembers(String tagid,String page,String keystr){//page=1 keystr=""
//    	showCustomToast("initGeGroupMembers1");
    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
				Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
		    	    ViewGroupMemberIQ reqXML = new ViewGroupMemberIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
		            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		    	    CurrentUsername = username;
//		            reqXML.setUsername(username);
		            reqXML.setTagid(tagid);
		            reqXML.setPage(page);
		            reqXML.setKeystr(keystr);
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
	//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "viewgroupmemberiq"; 
		    		String namespace = "com:isharemessage:viewgroupmemberiq";
		    		ViewGroupMemberIQResponseProvider provider = new ViewGroupMemberIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "viewgroupmemberiq", "com:isharemessage:viewgroupmemberiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof ViewGroupMemberIQResponse) {
		                	final ViewGroupMemberIQResponse viewGroupMemberIQResponse = (ViewGroupMemberIQResponse) rt;
	
		                    if (viewGroupMemberIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:viewgroupmemberiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = viewGroupMemberIQResponse.getId();
		                        String Apikey = viewGroupMemberIQResponse.getApikey();
		                        cGroups = viewGroupMemberIQResponse.getCGroups();
		                        AffiliationsCount = cGroups.size();
		                        if(cGroups.size()!=0){
			                        Log.e("响应packet结果解析...............", "Id="+Id+";Apikey="+Apikey); 
//			                        return true;
			                        Iterator iter = cGroups.entrySet().iterator();
			            			Map.Entry entry = null;
			            			Object key = null;
			            			Object val = null;
			            			ContactGroup cGroup = null;
			            			int idx = -1;
			            			String tmp = null;
			            			while (iter.hasNext()) {
			                			entry = (Map.Entry) iter.next();
			                			key = entry.getKey();
			                			val = entry.getValue();
			                			cGroup = (ContactGroup)val;
			                			cGroupsList.add(cGroup);
			                			//isfriend=true;2@0/allen
			                			System.out.println("al_rec.size()="+cGroups.size()+"uid-isfriend="+key+";"+cGroup.getUid()+"@0/"+cGroup.getUsername());
			                			//key的格式：value.get("isfriend")+""+p+"-"+value.get("ownerid")
			                			//isfriend为true或false , p为0自增长数， ownerid为群组用户user_id
			                			idx = ((String)key).indexOf("-");
			                			tmp = ((String)key).substring(idx+1);
			                			if(tmp!=null
			                					&& tmp.length()!=0
			                					&& !tmp.equalsIgnoreCase("null"))
			                				OwnerUid = tmp;
			                			if(OwnerUid.equalsIgnoreCase(cGroup.getUid())){
			                				OwnerUsername = cGroup.getUsername();
//			                				break;
			                			}
			            			}
		                        }
		                        String retcode = viewGroupMemberIQResponse.getRetcode();
		                        String memo = viewGroupMemberIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000")){
		                        	errorType = 0;
		                        	return true;
		                        }
		                        else if(retcode.equalsIgnoreCase("0002"))
		                        	errorType = 6;
		                        else
		                        	errorType = 5;
		                        
		                    }
		                } 
		            }
		    		errorType = 1;

		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
		return false;
    }
    
    
    private boolean initExitGroup(String tagid,String uids){//page=1 keystr=""
//    	showCustomToast("initGeGroupMembers1");
    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
				Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
		    	    ExitGroupIQ reqXML = new ExitGroupIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
		            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		    	    CurrentUsername = username;
//		            reqXML.setUsername(username);
		    	    reqXML.setUids(uids);
		            reqXML.setTagid(tagid);
		            reqXML.setOwnerid(OwnerUid);
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
	//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid+tagid+OwnerUid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "exitgroupiq"; 
		    		String namespace = "com:isharemessage:exitgroupiq";
		    		ExitGroupIQResponseProvider provider = new ExitGroupIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "exitgroupiq", "com:isharemessage:exitgroupiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof ExitGroupIQResponse) {
		                	final ExitGroupIQResponse exitGroupIQResponse = (ExitGroupIQResponse) rt;
	
		                    if (exitGroupIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:exitgroupiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = exitGroupIQResponse.getId();
		                        String Apikey = exitGroupIQResponse.getApikey();
		                        
		                        String retcode = exitGroupIQResponse.getRetcode();
		                        String memo = exitGroupIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000")){
		                        	errorType = 0;
		                        	return true;
		                        }
		                        else if(retcode.equalsIgnoreCase("0002"))
		                        	errorType = 6;
		                        else
		                        	errorType = 5;
		                        
		                    }
		                } 
		            }
		    		errorType = 1;

		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
		return false;
    }
    
    private Handler mHandler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case 0:
//			        if (cGroups.size() == 0) {
//			            finish();
//			            return;
//			        }
					break;
				case 1:
	        
//					memberItems.clear();
                    if (allMemberItems == null) {
						allMemberItems = new ArrayList<ContactGroup>();
					}
                    allMemberItems.clear();
                    allMemberItems.addAll(cGroupsList);
//                    if (AffiliationsCount<=15) {
//                    	memberItems.addAll(cGroupsList);
//                    	moreRl.setVisibility(View.GONE);
//					} else {
//						for (int i = 0; i < 15; i++) {
//							memberItems.add((ContactGroup)cGroupsList.get(i));
//							moreRl.setVisibility(View.VISIBLE);
//						}
//					}
                    
                    groupAdapter = null;
                	groupAdapter = new GridAdapter(GroupMemberActivity.this, allMemberItems);
                    groupListView.setAdapter(groupAdapter);
					break;
				case 2:
					showCustomToast("处理完成!");
					startActivity(new Intent(GroupMemberActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
					finish();	
					break;
				case 3:
					if(errorType!=5)
						showCustomToast(errorMsg[errorType]);
					break;
				default:
					break;
			}
		}
	};
	
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(GroupMemberActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(GroupMemberActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
//			getContactList(ConstantValues.refresh);
//			startActivity(new Intent(OtherProfileActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			Intent intent =  new Intent(GroupMemberActivity.this, ContactFrameActivity.class);
	    	intent.putExtra("refreshroster", "true");
			startActivity(intent);
			GroupMemberActivity.this.finish();
		}
	}
	//网络状态 start
			@Override
			public void connectionStatusChanged(int connectedState, String reason) {
				Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
				switch (connectedState) {
				case 0://connectionClosed
					mHandler3.sendEmptyMessage(0);
					break;
				case 1://connectionClosedOnError
//					mConnectErrorView.setVisibility(View.VISIBLE);
//					mNetErrorView.setVisibility(View.VISIBLE);
//					mConnect_status_info.setText("连接异常!");
					mHandler3.sendEmptyMessage(1);
					break;
				case 2://reconnectingIn
//					mNetErrorView.setVisibility(View.VISIBLE);
//					mConnect_status_info.setText("连接中...");
					mHandler3.sendEmptyMessage(2);
					break;
				case 3://reconnectionFailed
//					mNetErrorView.setVisibility(View.VISIBLE);
//					mConnect_status_info.setText("重连失败!");
					mHandler3.sendEmptyMessage(3);
					break;
				case 4://reconnectionSuccessful
//					mNetErrorView.setVisibility(View.GONE);
					mHandler3.sendEmptyMessage(4);

				default:
					break;
				}
			}
			Handler mHandler3 = new Handler() {

				@Override
				public void handleMessage(android.os.Message msg) {
					super.handleMessage(msg);
					switch (msg.what) {
					case 0:
						break;

					case 1:
						mNetErrorView.setVisibility(View.VISIBLE);
						if(BeemConnectivity.isConnected(mContext))
						mConnect_status_info.setText("连接异常!");
						break;

					case 2:
						mNetErrorView.setVisibility(View.VISIBLE);
						if(BeemConnectivity.isConnected(mContext))
						mConnect_status_info.setText("连接中...");
						break;
					case 3:
						mNetErrorView.setVisibility(View.VISIBLE);
						if(BeemConnectivity.isConnected(mContext))
						mConnect_status_info.setText("重连失败!");
						break;
						
					case 4:
						mNetErrorView.setVisibility(View.GONE);
						String udid = "";
						String partnerid = "";
						try{
							udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
							partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
						}catch(Exception e){
							e.printStackTrace();
						}
//						udidTextView.setText("udid="+udid);
//						partneridEditText.setText(partnerid);
//						getContactList();//20141025 added by allen
						break;
					case 5:
						mNetErrorView.setVisibility(View.VISIBLE);
						mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
						break;
					case 6:
						if(mXmppFacade!=null 
//								&& mXmppFacade.getXmppConnectionAdapter()!=null 
//								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
								&& BeemConnectivity.isConnected(mContext)){
							
						}else{
							mNetErrorView.setVisibility(View.VISIBLE);
							if(BeemConnectivity.isConnected(mContext))
							mConnect_status_info.setText("网络可用,连接中...");
						}
						break;	
					}
				}

			};
			private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
		        @Override
		        public void onReceive(Context context, Intent intent) {
		            String action = intent.getAction();  
		            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
		                Log.d("PoupWindowContactList", "网络状态已经改变");  
//		                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//		                info = connectivityManager.getActiveNetworkInfo();    
//		                if(info != null && info.isAvailable()) {  
//		                    String name = info.getTypeName();  
//		                    Log.d(tag, "当前网络名称：" + name);  
//		                    //doSomething()  
//		                } else {  
//		                    Log.d(tag, "没有可用网络");  
//		                  //doSomething()  
//		                }  
		                if(BeemConnectivity.isConnected(context)){
//		                	mNetErrorView.setVisibility(View.GONE);
//		                	isconnect = 0;
		                	mHandler3.sendEmptyMessage(6);//4
		                }else{
//		                	mNetErrorView.setVisibility(View.VISIBLE);
//		                	isconnect = 1;
		                	mHandler3.sendEmptyMessage(5);
		                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
		                }
		            } 
		        }
			};
			
			private boolean phonestate = false;//false其他， true接起电话或电话进行时 
		    /* 内部class继承PhoneStateListener */
		    public class exPhoneCallListener extends PhoneStateListener
		    {
		        /* 重写onCallStateChanged
		        当状态改变时改变myTextView1的文字及颜色 */
		        public void onCallStateChanged(int state, String incomingNumber)
		        {
		          switch (state)
		          {
		            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
		            case TelephonyManager.CALL_STATE_IDLE:
		            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
		            	if(phonestate){
		            		onPhoneStateResume();
		            	}
		            	phonestate = false;
		              break;
		            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
		            case TelephonyManager.CALL_STATE_OFFHOOK:
		            	Log.e("================20131216 接起电话时================", "接起电话时");
		            	onPhoneStatePause();
		            	phonestate = true;
		              break;
		            /* 电话进来时 :在通话的过程中*/
		            case TelephonyManager.CALL_STATE_RINGING:
//		              getContactPeople(incomingNumber);
		            	Log.e("================20131216 电话进来时================", "电话进来时");
//		            	onBackPressed();
		            	onPhoneStatePause();
		            	phonestate = true;
		              break;
		            default:
		              break;
		          }
		          super.onCallStateChanged(state, incomingNumber);
		        }
		    }
		    
		    protected void onPhoneStatePause() {
//				super.onPause();
		    	try{
//		    		try {
//		    		    if (mRoster != null) {
//		    			mRoster.removeRosterListener(mBeemRosterListener);
//		    			mRoster = null;
//		    		    }
//		    		} catch (RemoteException e) {
//		    		    Log.d("ContactList", "Remote exception", e);
//		    		}
					if (mBinded) {
						getApplicationContext().unbindService(mServConn);
					    mBinded = false;
					}
					mXmppFacade = null;
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
		    }
		    
		    protected void onPhoneStateResume() {
//				super.onResume();
		    	try{
				if (!mBinded){
//				    new Thread()
//				    {
//				        @Override
//				        public void run()
//				        {
				    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//				        }
//				    }.start();		    
				}
				if (mBinded){
//					mImageFetcher.setExitTasksEarly(false);
				}
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
		    }
		    
		    /*
		     * 打开设置网络界面
		     * */
		    public static void setNetworkMethod(final Context context){
		        //提示对话框
		        AlertDialog.Builder builder=new AlertDialog.Builder(context);
		        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
		            
		            @Override
		            public void onClick(DialogInterface dialog, int which) {
		                // TODO Auto-generated method stub
		                Intent intent=null;
		                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
		                if(android.os.Build.VERSION.SDK_INT>10){
		                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
		                }else{
		                    intent = new Intent();
		                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
		                    intent.setComponent(component);
		                    intent.setAction("android.intent.action.VIEW");
		                }
		                context.startActivity(intent);
		            }
		        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
		            
		            @Override
		            public void onClick(DialogInterface dialog, int which) {
		                // TODO Auto-generated method stub
		                dialog.dismiss();
		            }
		        }).show();
		    }
			//网络状态 end
}
